from machine import UART,Pin,RTC,SoftI2C
from wifi import connectWiFi,connectServer,GET,check_trigger_btn, upload_data,visit_msg_room,get_room_msg,getReceiveDataInfo
import time
import re
import ops
import json
import sys
import gc

oled_width = 128
oled_height = 64
ops.init_i2c(16,17,oled_width, oled_height)

def send_request():
    pass

def visit_micropython_html():
    connectServer('micropython.org')
    resp = GET('/ks/test.html')
    ops.show_text(resp)
    
def visit_echo_html():
    connectServer('echo.free.beeceptor.com')
    resp = GET('/')
    print(resp)
    
def visit_hanxiaoxin_html():
    connectServer('www.hanxiaoxin.cn')
    resp = GET('/')
    ops.show_text(resp)
    
def visit_hanxiaoxin_room_html():
    connectServer('www.hanxiaoxin.cn', 3000)
    resp = GET('/room')
    print(resp)
    
def visit_hanxiaoxin_msg_html():
    #connectWiFi()
    connectServer('www.hanxiaoxin.cn', 3000)
    resp = GET('/msg')
    print(resp)
    
def visit_codemao_btn(topic = "Tiot_qubXqCiP"):
    ops.show_text('connect server..')
    connectServer('creation-hardware.codemao.cn', 3000)
    ops.show_text('server connected...')
    upload_data(topic)
    ops.show_text('data uploaded...')
    while True:
        resp = check_trigger_btn(topic)
        if "Codemao_0" in resp:
            ops.show_text("Codemao_0")
        if "Codemao_1" in resp:
            ops.show_text("Codemao_1")
            time.sleep(3)
            machine.reset()
        time.sleep(2)

def query_actions():
    connectServer('www.hanxiaoxin.cn', 8080)
    resp = GET('/action?name=poem&device_id=4250304830333703')
    json_str = resp.decode()
    json_str = json_str.replace('CLOSED', '')
    json_str = re.sub(r"\+IPD,\d+:", "", json_str)
    #print(json_str)
    
    try:
        json_str = json_str.replace("\r\n", "")
        json_str = json_str.replace("\n", "")
        print(json_str)
        match = re.search(r'\{(.*?)\}$', json_str)
        print(match)
        if match:
            v = match.group(0)
            print(v)
            json_data = json.loads(v)
            actions = json_data["actions"]
            if len(actions) > 0:
                msg = actions[0]["action"]["data"]["content"]
                print("收到的poem: ",msg)
        
    except Exception as e:
        print("err:", e)
        
        
def visit_hanxiaoxin_room():
    query_actions()
    #show_text('connect server..')
    connectServer('www.hanxiaoxin.cn', 8080)
    #show_text('server connected...')
    resp = get_room_msg()
    json_str = resp.decode()
    #print(len(json_str))
    print(json_str)
    json_str = json_str.replace('CLOSED', '')
    json_str = re.sub(r"\+IPD,\d+:", "", json_str)
    #getReceiveDataInfo()
    try:
        with open("msg.json", "w") as outfile:
             outfile.write(json_str)
        match = re.search(r'\{(.*?)\}', json_str)
        if match:
            v = '{' + match.group(1) + '}'
            json_data = json.loads(v)
            msg = json_data['msg']
            font12 = json_data['font12']
            #print(msg)
            #print(font12)
            ops.set_font(font12, 12)
            ops.reset_line()
            ops.show_text(msg)
    except Exception as e:
        print(e)
    
    
    #ops.reset_line()
    #ops.show_text(v)
    
        

# 访问codemao_btn
def visit_codemao():
    ops.show_text('connect wifi...')
    connectWiFi()
    ops.show_text('connect ok...')
    visit_codemao_btn()

def visit_hanxiaoxin(count = 0):
    ops.show_text('connect wifi...')
    connectWiFi()
    ops.show_text('connect ok...')
    try:
        if count > 0:
            visit_hanxiaoxin_room()
        else:
            while True:
                gc.collect()
                free_m = gc.mem_free()
                alloc_m = gc.mem_alloc()
                print("free: ", free_m/1024, "KB alloc_m: ", alloc_m/1024, "KB")
                visit_hanxiaoxin_room()
                time.sleep(2)
    except Exception as e:
        sys.print_exception(e)
        time.sleep(5)
        visit_hanxiaoxin()
    

delay = 0.5
font_size = 12

try:
    #ops.show_text('    静夜思\n   床前明月光\n   疑是地上霜\n   举头望明月\n   低头思故乡', font_size, delay)
    #ops.show_text('静夜\n思床林波思床林波思床林波', font_size, delay)
    #ops.show_text('李白乘舟将欲行，忽闻岸上踏歌声。桃花潭水深千尺，不及汪伦送我情。')
    visit_hanxiaoxin()
    #visit_echo_html()
    #visit_hanxiaoxin_msg_html()
except Exception as e:
    with open("log.txt", 'a+') as f:
        f.write(str(e))
        f.write('\n')
    sys.print_exception(e)


    

